﻿#include "translatehelper.h"

#include <QGuiApplication>
#include <QQmlEngine>
#include <QLocale>

#include "settingshelper.h"

TranslateHelper::TranslateHelper(QObject *parent)
    : QObject{parent}
{
    _languages << "en_US" << "zh_CN";
    _current = SettingsHelper::getInstance()->getLanguage(getLocaleLanguage());
}

void TranslateHelper::init(QQmlEngine *engine)
{
    _engine = engine;
    _translator = new QTranslator(this);
    QGuiApplication::installTranslator(_translator);
    QString translatorDir = QGuiApplication::applicationDirPath() + "/i18n";
    QString translatorPath = QString::fromStdString("%1/SecAssistPro_%2.qm").arg(translatorDir, _current);
    if (_translator->load(translatorPath)) {
        _engine->retranslate();
    } else {
        qDebug() << __func__ << "failure.";
    }
}

QString TranslateHelper::getLocaleLanguage()
{
    QLocale locale;
    QString ret("en_US");
    if (locale.language() == QLocale::Language::Chinese) {
        ret = "zh_CN";
    } else if (locale.language() == QLocale::Language::English) {
        ret = "en_US";
    }
    qDebug() << __func__ << ret;
    return ret;
}

void TranslateHelper::switchLanguage(const QString &language)
{
    QTranslator *translator = new QTranslator(this);
    QString translatorDir = QGuiApplication::applicationDirPath() + "/i18n";
    QString translatorPath = QString::fromStdString("%1/SecAssistPro_%2.qm").arg(translatorDir, _current);
    qDebug() << __func__ << translatorPath;
    if (translator->load(translatorPath)) {
        QGuiApplication::instance()->removeTranslator(_translator);
        delete _translator;
        _translator = translator;
        QGuiApplication::installTranslator(translator);
        _engine->retranslate();
    } else {
        delete translator;
        translator = nullptr;
        qDebug() << __func__ << "failure.";
    }
}

TranslateHelper::~TranslateHelper() = default;

